import axios from "axios"
import store from "../store"
import QS from "qs"
import {
  Loading,
  Message
} from "element-ui"
import {
  getToken,
  setToken
} from '@/utils/auth'
let loading = ""
let flag = 0
const CancelToken = axios.CancelToken
const source = CancelToken.source()
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 60000,
  cancelToken: source.token
})
// 不展示loading的请求url
const noLoadingReq = ["/dict/selectByType", "/jobRealTime/realRateMonitoring", "/log/job/realTime", "/log/totalNumber"]

service.interceptors.request.use(function (config) {
  flag++
  config.headers.Authorization = getToken()
  if (config.method === "get" && config.data) {
    config.url = config.url + "?" + QS.stringify(config.data)
  }
  if (noLoadingReq.indexOf(config.url) === -1) {
    loading = Loading.service({
      lock: true,
      text: "Loading",
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)"
    })
  }
  // config.headers.Authorization = "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxLGFkbWluIiwiaXNzIjoiYWRtaW4iLCJleHAiOjE2MjAyODcyOTgsImlhdCI6MTYxNzY5NTI5OCwicm9sIjoiUk9MRV9BRE1JTiJ9.5GpTVFYOg1EYrimmTZQXgBfAPN9IE-83O_JYlkprKycFntDly9kbe5PPvQhoeVOqHUHmWZ0Dmzcu33dAyRN_gQ"
  // console.log(store.state);
  config.headers.token = store.state.user.token;
  return config
}, function (error) {
  return Promise.reject(error)
})


service.interceptors.response.use(function (response) {
  flag--
  if (!flag && loading) {
    loading.close()
  }
  // if (!response.data.success && response.data.data === 'ErrorToLogin') {
  if (!response.data.success && response.data.message === "invalid token") {
    Message.error(response.data.message)
    store.dispatch("LogOut")
  }
  return response
}, function (error) {
  flag--
  if (loading) {
    loading.close()
  }
  Message.error(error.request.statusText || "服务链接失败")
  return Promise.reject(error)
})
export default service
